use std::time::Duration;

mod common;

fn main() {
    common::init_logger();
    common::build_async_runtime(run_internal());
}

async fn run_internal() {
    let hosts = vec![
        ("192.168.128.142".to_string(), 6401),
        ("192.168.128.142".to_string(), 6402),
    ];
    let builder = redius::client::RedisClientBuilder::new_cluster(hosts)
        .password("111111")
        .reconnect_interval(Duration::from_secs(2))
        .receive_timeout(Duration::from_secs(15))
        .timeout(Duration::from_secs(55))
        .client_name("redius-example".to_string());
    let client = match builder.build_and_connect().await {
        Ok(client) => {
            client
            // log::info!("connect success");
        }
        Err(err) => {
            log::error!("{err}");
            return;
        }
    };
    match client.string_set("a", "dasdasdasd").await {
        Ok(_) => {
            log::info!("set success");
        }
        Err(err) => {
            log::error!("{err:?}");
        }
    }
    match client.string_get("a").await {
        Ok(Some(a)) => {
            log::info!("a = {a}");
        } 
        Ok(None) => {
            log::info!("a is None");
        }
        Err(err) => {
            log::error!("{err:?}");
        }
    }
    let mut stream = match client.subscribe("abc").await {
        Ok(stream) => stream,
        Err(err) => {
            log::error!("{err:?}");
            return;
        }
    };
    loop {
        match stream.recv().await {
            Ok(Some(message)) => match String::from_utf8(message.content) {
                Ok(str) => {
                    if str == "exit" {
                        log::debug!("subscribe exit");
                        break;
                    } else {
                        log::info!(
                            "receive from channel = {}, content = {}",
                            message.channel,
                            str
                        )
                    }
                }
                Err(err) => {
                    log::error!("{err:?}");
                }
            },
            Ok(None) => {
                break;
            }
            Err(err) => {
                log::error!("{err:?}");
                return;
            }
        }
    }
    let _client = match stream.exit().await {
        Ok(client) => client,
        Err(err) => {
            log::error!("{err:?}");
            return;
        }
    };
    log::info!("press ctrl+c key to exit");
    match tokio::signal::ctrl_c().await {
        Ok(_) => {
            log::info!("exit, bye bye ~");
        }
        Err(err) => {
            log::error!("{}", err);
        }
    }
}
